<template>
    <div class="box">
        <div class="top">
            <h1>订单管理</h1>
        </div>
        <div class="content">
            <div class="con-top">
                <el-form :model="form" ref="formRef" label-width="100px">
                    <div class="horizontal">
                        <el-form-item label="订单号">
                            <el-input v-model="form.orderNo" style="width: 200px;" placeholder="请输入订单号" />
                        </el-form-item>

                        <el-form-item label="收货人">
                            <el-input v-model="form.consignee" style="width: 200px;" placeholder="请输入收货人" />
                        </el-form-item>

                        <el-form-item label="手机号">
                            <el-input v-model="form.phone" style="width: 200px;" placeholder="请输入手机号" />
                        </el-form-item>
                    </div>

                    <div class="horizontal">
                        <el-form-item label="订单状态">
                            <el-select v-model="form.orderState" style="width: 250px;" placeholder="请选择订单状态">
                                <el-option label="已处理" value="已处理" />
                                <el-option label="派送中" value="派送中" />
                                <el-option label="已完成" value="已完成" />
                            </el-select>
                        </el-form-item>

                        <el-form-item label="选择时间">
                            <el-date-picker v-model="value" type="datetimerange" :shortcuts="shortcuts"
                                range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" />
                        </el-form-item>

                        <el-form-item>
                            <el-button type="primary" :icon="Search" style="margin-left: -90px;"
                            @click="handleSearch">搜索</el-button>
                        </el-form-item>

                    </div>

                </el-form>


                <el-table :data="tableData" stripe style="width: 100%;height: 380px;">
                    <el-table-column prop="orderNo" label="订单号" />
                    <el-table-column prop="orderTime" label="下单时间">
                        <template #default="scoped">
                            {{ dataTime(scoped.row.orderTime) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="phone" label="联系电话" />
                    <el-table-column prop="consignee" label="收货人" />
                    <el-table-column prop="deliverAddress" label="送货地址" />
                    <el-table-column prop="deliveryTime" label="送达时间">
                        <template #default="scoped">
                            {{ dataTime(scoped.row.deliveryTime) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="remarks" label="备注" />
                    <el-table-column prop="orderAmount" label="订单金额" />
                    <el-table-column prop="orderState" label="订单状态" />
                    <el-table-column label="操作">
                        <template #default="scoped">
                            <!-- 使用 el-button-group 组件让按钮并排显示 -->
                            <el-button-group>
                                <el-button type="primary" size="small"
                                    @click="viewDetails(scoped.row.id)">查看</el-button>
                                <el-button type="primary" size="small"
                                    @click="handleEdit(scoped.row)"
                                >编辑</el-button>
                            </el-button-group>
                        </template>
                    </el-table-column>
                </el-table>

                <div class="demo-pagination-block">
                    <el-pagination v-model:current-page="formData.currentPage" v-model:page-size="formData.pageSize"
                        :page-sizes="[5, 10, 15, 20]" :size="size" :disabled="disabled" :background="background"
                        layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                        @current-change="handleCurrentChange" />
                </div>
            </div>
        </div>

        <el-dialog v-model="dialogFormVisible" title="订单详情" width="800px">
            <el-table :data="[detailData]" style="width: 100%;">
                <el-table-column prop="orderNo" label="订单号" />
                <el-table-column prop="orderTime" label="下单时间">
                    <template #default="scoped">
                        {{ dataTime(scoped.row.orderTime) }}
                    </template>
                </el-table-column>
                <el-table-column prop="phone" label="联系电话" />
                <el-table-column prop="consignee" label="收货人" />
                <el-table-column prop="deliverAddress" label="送货地址" />
                <el-table-column prop="deliveryTime" label="送达时间">
                    <template #default="scoped">
                        {{ dataTime(scoped.row.deliveryTime) }}
                    </template>
                </el-table-column>
                <el-table-column prop="remarks" label="备注" />
                <el-table-column prop="orderAmount" label="订单金额" />
                <el-table-column prop="orderState" label="订单状态" />
            </el-table>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">关闭</el-button>
                </div>
            </template>
        </el-dialog>

         <!-- 新增编辑弹窗 -->
    <el-dialog v-model="editDialogVisible" title="编辑订单" width="800px">
        <el-form :model="editForm" ref="editFormRef" :label-width="formLabelWidth">
            <el-form-item label="订单号">
                <el-input v-model="editForm.orderNo" />
            </el-form-item>
            <el-form-item label="下单时间">
                <el-date-picker v-model="editForm.orderTime" type="datetime" />
            </el-form-item>
            <el-form-item label="联系电话">
                <el-input v-model="editForm.phone" />
            </el-form-item>
            <el-form-item label="收货人">
                <el-input v-model="editForm.consignee" />
            </el-form-item>
            <el-form-item label="送货地址">
                <el-input v-model="editForm.deliverAddress" />
            </el-form-item>
            <el-form-item label="送达时间">
                <el-date-picker v-model="editForm.deliveryTime" type="datetime" />
            </el-form-item>
            <el-form-item label="备注">
                <el-input v-model="editForm.remarks" type="textarea" />
            </el-form-item>
            <el-form-item label="订单金额">
                <el-input-number v-model="editForm.orderAmount" :min="0" />
            </el-form-item>
            <el-form-item label="订单状态">
                <el-select v-model="editForm.orderState">
                    <el-option label="已处理" value="已处理" />
                    <el-option label="派送中" value="派送中" />
                    <el-option label="已完成" value="已完成" />
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="editDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitEdit">确定</el-button>
            </div>
        </template>
    </el-dialog>

    </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import { Search } from '@element-plus/icons-vue'
import { getDetail, getList ,editDetail} from '../api/order'
import { time } from 'echarts'

const background = ref(true)
const disabled = ref(false)
// script部分添加
const detailData = ref({}) // 专门存储单个订单详情
const total = ref(0)
const formData = reactive({
    currentPage: 1,
    pageSize: 5
})

const dialogFormVisible = ref(false)
const formLabelWidth = '140px'
const value = ref([])
const tableData = ref([])

const dataTime = (time) => {
    return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}

const form = reactive({
    data: '',//订单数据对象
    id: '', // 订单id
    orderNo: '', // 订单号
    orderTime: '', // 下单时间
    phone: '', // 手机号
    consignee: '', // 收货人
    deliverAddress: '', // 送货地址
    deliveryTime: '', // 送达时间
    remarks: '', // 备注
    orderAmount: '', // 订单金额
    orderState: '', // 订单状态
})

const editDialogVisible = ref(false)
const editForm = reactive({
    id: '',
    orderNo: '',
    orderTime: '',
    phone: '',
    consignee: '',
    deliverAddress: '',
    deliveryTime: '',
    remarks: '',
    orderAmount: 0,
    orderState: ''
})
const editFormRef = ref()

const formRef = ref()

const shortcuts = [
    {
        text: '近5天',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setDate(start.getDate() - 5)
            return [start, end]
        },
    },
    {
        text: '近一周',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setDate(start.getDate() - 7)
            return [start, end]
        },
    },
    {
        text: '近一个月',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setMonth(start.getMonth() - 1)
            return [start, end]
        },
    },
    {
        text: '近三个月',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setMonth(start.getMonth() - 3)
            return [start, end]
        },
    },
]

// 获取订单列表
const getOderList = async () => {
    const res = await getList(formData)
    console.log(res);
    tableData.value = res.data;
    total.value = res.total;
}
getOderList()

const handleSizeChange = (val) => {
    getOderList()
}
const handleCurrentChange = (val) => {
    getOderList()
}

// 查看订单详情
const viewDetails = async (id) => {
    const res = await getDetail({ id })
    console.log(res);
    detailData.value = res.data;
    dialogFormVisible.value = true;
}

// 编辑订单
const handleEdit = (row) => {
    Object.assign(editForm, row)
    editDialogVisible.value = true
}

const submitEdit = async () => {
    try {
        const res = await editDetail(editForm)
        if (res.code === 0) {
            editDialogVisible.value = false
            ElMessage({
                type: 'success',
                message: '订单信息修改成功'
            })
            getOderList() // 刷新订单列表
        } else {
            ElMessage({
                type: 'error',
                message: '订单信息修改失败'
            })
        }
    } catch (error) {
        console.error('编辑订单时出错:', error)
        ElMessage({
            type: 'error',
            message: '编辑订单时出错，请稍后重试'
        })
    }
}

// 搜索订单
const handleSearch = async () => {
    // 合并分页信息和搜索表单的筛选条件
    const searchParams = {
        ...formData,
        ...form,
        // 处理状态
        ...(form.orderState && { orderState: form.orderState }),
        // 处理日期范围
        ...(value.value.length > 0 && {
            startTime: dayjs(value.value[0]).format('YYYY-MM-DD HH:mm:ss'),
            endTime: dayjs(value.value[1]).format('YYYY-MM-DD HH:mm:ss')
        })
    };

    try {
        const res = await getList(searchParams);
        console.log(res);
        tableData.value = res.data;  // 更新表格数据
        total.value = res.total; // 更新总记录数
        formData.currentPage = 1; // 搜索后重置到第一页
    } catch (error) {
        console.error('搜索订单时出错:', error);
        ElMessage({
            type: 'error',
            message: '搜索订单时出错，请稍后重试'
        });
    }
};
</script>

<style scoped>
.box {
    width: 100%;
    /* height: 100%; */
    /* display: flex; */
    background-color: #fff;
    border-radius: 6px;

}

.top {
    width: 100%;
    height: 6%;
    font-size: 18px;
    /* font-weight: bold; */
    border-bottom: 1px solid #888787;
}

.top h1 {
    margin-left: 20px;
    line-height: 40px;
}

.content {
    width: 100%;
    height: 94%;
    /* display: flex; */
}

.con-top {
    width: 100%;
    margin-top: 20px;
    /* height: 100%; */
    /* display: flex;
    flex-wrap: nowrap; */
}

.horizontal {
    display: flex;
    flex-wrap: nowrap;
    align-items: center;
    /* 垂直居中对齐 */
}

.demo-pagination-block {
    margin-top: 20px;
    padding: 0 20px;
}
</style>

<style>
/* 修改偶数行（默认行）的背景颜色 */
.el-table__body tr td {
    background-color: #f3e07a;
    /* 可根据需求修改颜色 */
}

/* 修改奇数行（斑马纹行）的背景颜色 */
.el-table--striped .el-table__body tr.el-table__row--striped td {
    background-color: #71a9fd !important;
    /* 可根据需求修改颜色 */
}

/* 修改鼠标悬停时偶数行的背景颜色 */
.el-table__body tr:hover td {
    background-color: #e6f7ff;
    /* 可根据需求修改颜色 */
}

/* 修改鼠标悬停时奇数行的背景颜色 */
.el-table--striped .el-table__body tr.el-table__row--striped:hover td {
    background-color: #e6f7ff !important;
    /* 可根据需求修改颜色 */
}
</style>